package wh.coach.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

/**
 * @Author xhw
 * @Date 2023/10/7
 * @Version 1.0
 */
public class ListToStringTypeHandler implements TypeHandler<List<String>> {
    @Override
    public List<String> getResult(final ResultSet rs, final String columnName) throws SQLException {
        String addressStr = rs.getString(columnName);
        if (addressStr == null || addressStr.trim().isEmpty()) { // 如果 address 为空或空串
            return new ArrayList<>(); // 返回空列表
        } else {
            return convertAddressStrToList(addressStr);
        }
    }

    @Override
    public List<String> getResult(final ResultSet rs, final int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public List<String> getResult(final CallableStatement cs, final int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public void setParameter(final PreparedStatement ps, final int i, final List<String> parameter, final JdbcType jdbcType) throws SQLException {
        if (parameter != null && !parameter.isEmpty()) {
            StringJoiner joiner = new StringJoiner(",");
            for (String str : parameter) {
                joiner.add(str);
            }
            ps.setString(i, joiner.toString());
        } else {
            ps.setNull(i, Types.VARCHAR);
        }
    }

    private List<String> convertAddressStrToList(String addressStr) {
        if (addressStr == null || addressStr.trim().isEmpty()) {
            return new ArrayList<>();
        } else {
            return Arrays.asList(addressStr.split(","));
        }
    }
}
